package com.qdlc.p2p.dal.dao.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.qdlc.p2p.common.constant.Global;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.dal.common.SystemConfigHelper;
import com.qdlc.p2p.dal.common.SystemConfigHelper.Nid;
import com.qdlc.p2p.dal.common.dao.jpa.BaseDaoImpl;
import com.qdlc.p2p.dal.common.model.jpa.OrderFilter.OrderType;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.common.model.jpa.QueryParam;
import com.qdlc.p2p.dal.common.model.jpa.SearchFilter;
import com.qdlc.p2p.dal.common.model.jpa.SearchFilter.Operators;
import com.qdlc.p2p.dal.dao.AccountLogHisDao;
import com.qdlc.p2p.dal.dto.AccountLogHis;
import com.qdlc.p2p.dal.model.AccountLogHisModel;
import com.qdlc.p2p.dal.util.SystemConfigs;

@Repository("accountLogHisDao")
public class AccountLogHisDaoImpl extends BaseDaoImpl<AccountLogHis> implements AccountLogHisDao {

    @Override
    public PageDataList<AccountLogHisModel> accountLogList(AccountLogHisModel model, int pageNumber, int pageSize) {
        QueryParam param = QueryParam.getInstance().addPage(pageNumber, pageSize);

        if (!StringUtil.isBlank(model.getSearchName())) {
            SearchFilter orFilter1 = new SearchFilter("user.userName", Operators.LIKE, model.getSearchName().trim());
            param.addOrFilter(orFilter1, orFilter1);
        } else {
            if (StringUtil.isNotBlank(model.getStartTime())) {
                Date start = DateUtil.valueOf(model.getStartTime() + " 00:00:00");
                param.addParam("addTime", Operators.GTE, start);
            }
            if (StringUtil.isNotBlank(model.getEndTime())) {
                Date end = DateUtil.valueOf(model.getEndTime() + " 23:59:59");
                param.addParam("addTime", Operators.LTE, end);
            }
            if (StringUtil.isNotBlank(model.getUserName())) {
                param.addParam("user.userName", Operators.LIKE, model.getUserName().trim());
            }
        }
        param.addOrder(OrderType.DESC, "id");
        PageDataList<AccountLogHis> pageDateList = super.findPageList(param);
        PageDataList<AccountLogHisModel> pageDateList_ = new PageDataList<AccountLogHisModel>();
        List<AccountLogHisModel> list = new ArrayList<AccountLogHisModel>();
        pageDateList_.setPage(pageDateList.getPage());
        if (pageDateList.getList().size() > 0) {
            for (int i = 0; i < pageDateList.getList().size(); i++) {
                AccountLogHis c = pageDateList.getList().get(i);
                AccountLogHisModel cm = AccountLogHisModel.instance(c);
                cm.setUserName(c.getUser().getUserName());
                Long adminId = SystemConfigHelper.getLongValue(Nid.ADMIN_ACCOUNT);
                if (c.getToUser() != null && c.getToUser().getUserId() != adminId) {
                    cm.setToUserName(c.getToUser().getUserName());
                }
                if (c.getToUser() == null || c.getToUser().getUserId() == adminId) {
                    cm.setToUserName(SystemConfigs.WEB_NAME);
                }
                list.add(cm);
            }
        }
        pageDateList_.setList(list);
        return pageDateList_;
    }

    @Override
    public double getFeeByTypeAndDate(String type, String date) {
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT IFNULL(SUM(money),0) FROM ");
        sql.append(Global.DB_PREFIX).append("account_log");
        sql.append(" where type=? and date_format(add_time,'%Y-%m')=? ");
        Query query = em.createNativeQuery(sql.toString())
                .setParameter(1, type)
                .setParameter(2, date);
        Object obj = query.getSingleResult();
        return Double.parseDouble(obj.toString());
    }

    @Override
    public double todayEarnAmount(long userId) {
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT IFNULL(SUM(money),0) FROM ");
        sql.append(Global.DB_PREFIX).append("account_log");
        sql.append(" WHERE user_id = :userId AND payments_type = 1 AND date_format(add_time,'%Y-%m-%d') = :today ");
        Query query = em.createNativeQuery(sql.toString());
        query.setParameter("userId", userId);
        query.setParameter("today", DateUtil.dateStr2(DateUtil.getNow()));
        Object obj = query.getSingleResult();
        return Double.parseDouble(obj.toString());
    }

    @Override
    public double earnAmount(long userId) {
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT IFNULL(SUM(money),0) FROM ");
        sql.append(Global.DB_PREFIX).append("account_log");
        sql.append(" WHERE user_id = :userId AND payments_type = 1 ");
        Query query = em.createNativeQuery(sql.toString());
        query.setParameter("userId", userId);
        Object obj = query.getSingleResult();
        return Double.parseDouble(obj.toString());
    }

    @Override
    public double earnAmount() {
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT IFNULL(sum(money),0) from ");
        sql.append(Global.DB_PREFIX).append("account_log");
        sql.append(" WHERE payments_type = 1 ");
        Query query = em.createNativeQuery(sql.toString());
        Object obj = query.getSingleResult();
        return Double.parseDouble(obj.toString());
    }

    @Override
    public double amount(String type, String month) {
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT IFNULL(sum(money),0) from ");
        sql.append(Global.DB_PREFIX).append("account_log");
        sql.append(" WHERE type = :type AND date_format(add_time,'%Y-%m') = :month");
        Query query = em.createNativeQuery(sql.toString());
        query.setParameter("type", type);
        query.setParameter("month", month);
        Object obj = query.getSingleResult();
        return Double.parseDouble(obj.toString());
    }

    @Override
    public double amount(String[] type, String month) {
        if (type == null || type.length == 0) {
            return 0;
        }
        StringBuffer sql = new StringBuffer("SELECT IFNULL(sum(money),0) from ");
        sql.append(Global.DB_PREFIX).append("account_log");
        sql.append(" WHERE type in (");
        for (int i = 0; i < type.length; i++) {
            sql.append("?");
            if (i < type.length - 1) {
                sql.append(",");
            }
        }
        sql.append(") AND date_format(add_time,'%Y-%m') = :month");
        Query query = em.createNativeQuery(sql.toString());
        for (int i = 0; i < type.length; i++) {
            query.setParameter(i + 1, type[i]);
        }
        query.setParameter("month", month);
        Object obj = query.getSingleResult();
        return Double.parseDouble(obj.toString());
    }
}
